<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 信息提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <!-- 步骤条区域 -->
      <el-steps
        :space="300"
        :active="alertActive - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs 切换区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="alertActive"
          tab-position="left"
          :before-leave="butactive"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="ruleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="ruleForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="ruleForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cart">
              <el-cascader
                expand-trigger="hover"
                :options="catelist"
                :props="cascader"
                v-model="ruleForm.goods_cat"
                @change="handleChange"
                clearable
                change-on-select
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="(item, index) in commodityList"
              :key="index"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="temp"
                  v-for="(temp, key) in item.attr_vals"
                  :key="key"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in attributeList"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="remove"
              list-type="picture"
              :headers="headers"
              :on-success="success"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="ruleForm.goods_introduce"></quill-editor>
            <el-button class="button" type="primary" @click="add('ruleForm')"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      // tab标签切换索引
      alertActive: "0",
      // from表单数据
      ruleForm: {
        goods_name: "111",
        goods_price: 10,
        goods_weight: 10,
        goods_number: 10,
        goods_cat: [], // 商品分类选中的数据
        pics: [], // 上传图片地址
        goods_introduce: "", //富文本编辑器内容
        attrs: []
      },
      // 表单验证
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      // 商品分类下拉框数据
      catelist: [],
      // 指定级联选择器的配置对象
      cascader: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 选中的父级分类的ID值数组
      ballModel: [],
      // 商品参数数据
      commodityList: [],
      // 商品属性数据
      attributeList: [],
      // 图片上传的地址
      uploadURL: "http://api.xiaomadagege.cn:8800/api/private/v1/upload",
      // 设置上传的请求头部
      headers: { Authorization: window.sessionStorage.getItem("token") }
    };
  },
  methods: {
    // 商品分类下拉框数据
    async goods_cascader() {
      const result = await this.$http.get("categories");
      if (result.meta.status == 200) {
        this.catelist = result.data;
        this.$message.success("获取商品分类数据成功！");
      } else {
        this.$message.error("获取商品分类数据失败！");
      }
    },
    // 下拉框发生变化触发这个事件
    handleChange() {
      if (this.ruleForm.goods_cat.length !== 3) {
        this.ruleForm.goods_cat = [];
      }
    },
    // 标签页切换事件
    butactive(activeName, oldActiveName) {
      console.log(activeName);
      if (this.ruleForm.goods_cat.length !== 3 && oldActiveName == 0) {
        this.$message.error("请选择商品分类！");
        return false;
      }
    },
    // Tab页被选中时触发事件
    async tabClick() {
      if (this.alertActive == 1) {
        const result = await this.$http.get(
          `categories/${this.ruleForm.goods_cat[2]}/attributes`,
          { params: { sel: "many" } }
        );
        if (result.meta.status == 200) {
          result.data.forEach(item => {
            item.attr_vals =
              item.attr_vals.length == 0 ? [] : item.attr_vals.split(",");
          });
          this.commodityList = result.data;
          console.log(this.commodityList);
          this.$message.success("获取商品参数数据成功！");
        } else {
          this.$message.error("获取商品参数数据失败！");
        }
      }
      if (this.alertActive == 2) {
        const result = await this.$http.get(
          `categories/${this.ruleForm.goods_cat[2]}/attributes`,
          { params: { sel: "only" } }
        );
        if (result.meta.status == 200) {
          this.attributeList = result.data;
          console.log(this.attributeList);
          this.$message.success("获取商品参数数据成功！");
        } else {
          this.$message.error("获取商品参数数据失败！");
        }
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      console.log(file);
      this.previewPath = file.response.data.url;
      this.previewVisible = true;
    },
    // 删除图片事件
    remove(file) {
      const res = file.response.data.tmp_path;
      const i = this.ruleForm.pics.findIndex(item => {
        return item.pic === res;
      });
      this.ruleForm.pics.splice(i, 1);
      console.log(this.ruleForm);
    },
    // 文件上传成功事件
    success(response) {
      const pic = { pic: response.data.tmp_path };
      this.ruleForm.pics.push(pic);
      console.log(this.ruleForm);
    },
    // 添加商品事件
    add(ruleForm) {
      this.$refs[ruleForm].validate(async valid => {
        if (valid) {
          // lodash cloneDeep(obj) 深拷贝
          const from = _.cloneDeep(this.ruleForm);
          from.goods_cat = from.goods_cat.join(",");
          // 商品参数数据
          this.commodityList.forEach(item => {
            const newIfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(",")
            };
            this.ruleForm.attrs.push(newIfo);
          });
          // 商品属性数据
          this.attributeList.forEach(item => {
            const newIfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            };
            this.ruleForm.attrs.push(newIfo);
          });
          from.attrs = this.ruleForm.attrs;
          console.log(from);
          // 发起数据请求
          const result = await this.$http.post("goods", from);
          if (result.meta.status == 201) {
            this.$message.success("添加商品成功！");
            this.$router.push({ path: "/goods" });
          } else {
            this.$message.error("添加失败！");
          }
          if (result.meta.status == 400)
            return this.$message.error("商品名称已存在！");
        } else {
          this.$message.error("请输入对应的参数！");
        }
      });
    }
  },
  created() {
    this.goods_cascader();
  }
};
</script>

<style lang="stylus" scoped>
.el-steps {
  margin: 26px 0 26px 0;
}

.el-checkbox {
  margin: 0 10px 10px 0 !important;
}

.button {
  margin-top: 20px;
}
</style>
